#include "Thread.h"

namespace BASE{
void * func(void *arg){
	Thread * th = (Thread*)arg;
	th->thread();
	return NULL;
}

Thread::Thread():mIsRunning(0), tid(-1){

}

Thread::~Thread(){
	stop();
	if (tid > 0){
		pthread_join(tid, NULL);
	}
}

void Thread::start(){
	pthread_create(&tid, NULL, func, this);	
	__sync_fetch_and_add(&mIsRunning, 1);
}

void Thread::stop(){
	__sync_lock_test_and_set(&mIsRunning, 0);
}

bool Thread::isRunning(){
	return __sync_fetch_and_add(&mIsRunning, 0) == 1;
}

}

#ifdef TEST
using namespace BASE;
#include <iostream>
class ThreadTest: public Thread{
	void thread(){
		while(isRunning()){
			std::cout << "run test" << std::endl;
		}
	}
};

int main(){
	ThreadTest thread;
	thread.start();
	sleep(2);
	return 0;
}
#endif
